import {
  deleteTrainingPlanUsingPost,
  listTrainingPlanVoByPageUsingPost,
} from '@/services/backend/trainingPlanController';
import { listTrainingRuleByPageUsingPost } from '@/services/backend/trainingRuleController';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Tag, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import CreateModal from './components/CreateModal';

interface RuleOption {
  label: string; // 显示的名称
  value: string; // 选项的值
}

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();

  const [ruleEnumMap, setRuleEnumMap] = useState<RuleOption[]>([]);

  const loadRuleList = async () => {
    try {
      const { data, code } = await listTrainingRuleByPageUsingPost({});
      if (code === 0 && data?.records) {
        // 构建 ruleEnumMap
        const ruleEnumArray = data.records.map((rule: API.TrainingRule) => ({
          label: rule.ruleName, // 显示的名称
          //@ts-ignore
          value: rule.id.toString(), // 选项的值
        })) as RuleOption[];
        console.log(ruleEnumArray);
        setRuleEnumMap(ruleEnumArray); // 更新为数组格式
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  useEffect(() => {
    loadRuleList();
  }, []);

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.TrainingPlan) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteTrainingPlanUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  const columns: ProColumns<API.TrainingPlanVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '计划名称',
      dataIndex: 'planName',
      valueType: 'text',
    },
    {
      title: '计划描述',
      dataIndex: 'description',
      valueType: 'text',
    },
    {
      title: '计划规则',
      dataIndex: 'ruleList',
      valueType: 'select',
      fieldProps: {
        mode: 'multiple', // 设置为多选模式
        options: ruleEnumMap,
        placeholder: '请选择计划规则', // 提示文本
      },
      render: (dom, entity) => {
        return (
          <>
            {entity.ruleList?.map((rule) => {
              return (
                <Tag key={rule.trainingRuleId} color={"blue"} >
                  {rule.ruleName}
                </Tag>
              );
            })}
          </>
        );
      },
      hideInSearch: true,
    },
    {
      title: '开始时间',
      sorter: true,
      dataIndex: 'startTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '结束时间',
      sorter: true,
      dataIndex: 'endTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '计划状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '开启', status: 'active' },
        archived: { text: '关闭', status: 'inactive' },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.TrainingPlan>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listTrainingPlanVoByPageUsingPost({
            ...params,
            sortOrder,
            ...filter,
          } as API.TrainingPlanQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
